/*!
 @header AddressBookViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/31 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

//  -业务逻辑细节说明-
//
//  @abstract       本类用于读取系统通讯簿，并提供联系人选择后，向这些联系人发送短信的功能。
//

//  @discussion     实现了UISearchBar的功能，方便用户查找选择。

//  @notes          6.0后iOS加入了隐私保护，读取前必须识别版本，并使用不同版本的代码来创建地址薄Ref


//  @abstract       选择联系人电话时，会根据联系人的电话个数做不同的处理。
//

//  @discussion     1、如果联系人电话只有一个，那么就直接标记电话号码和联系人（注：每个电话号码都有一个status的属性来标识，标记用户已选择了此号码，当一个联系有多个号码时，会很有用），再次点击此联系人就会取消标记；
//                  2、如果联系人电话至少有两个，那么就会弹出电话号码选择框，一次只能选择一个号码，被选择的号码会被标记。再次点击此号码就会取消选择标记。
//
//                  3、如果联系人没有可用的电话，就提示用户。

//  @notes          


//  -类修改日志-
//  修改人   修改时间      针对版本           修改描述

//  周益     2013-4-16    1.0.0          概括：支持选择一个联系人的多个电话号码；           
//                                      原先只是添加第一个号码改为所有号码都添加进来；
//                                      支持右边section的字母索引选择


//  周益     2013-5-29    1.0.0          添加圈子成员接口变化，要求传入联系人姓名            


//  周益     2013-5-30    1.0.0          联系人有多个号码时，只能选择一个


#import "ABInvitationViewController.h"
#import "Config.h"
#import "Helper.h"
#import <AddressBook/AddressBook.h>
#import <MessageUI/MessageUI.h>
#import "pinyin.h"
#import "MBProgressHUD.h"
#import "MLTableAlert.h"
#import "JMFBase.h"
#import "MoonHTTPRequest.h"
#import "Contact.h"
#import "InvitationMessageViewController.h"


@interface ABInvitationViewController ()

@end

@implementation ABInvitationViewController

@synthesize circle = _circle;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        _canRefreshTableView = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

///////从分组类型改为了Plain类型，出现了白色和背景色交叉的问题，因此去掉了下面两行。Ben-2013.03.09
//    //视图背景
//    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
//    self.tableView.backgroundView = nil;
    self.title = _L(@"vc_title_106");
    
    //左侧导航按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
   
    //右侧导航按钮：邀请
    UIButton *inviteButton = [Helper buttonWithStyle:ButtonStyleNavigationInvite];
    [inviteButton addTarget:self action:@selector(inviteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:inviteButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    if (_names == nil) {
        _names = [[NSMutableArray alloc] init];
    }
    
    [self loadContacts];
    
    [self sectionInitData];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 40.5f)];
    
//    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dynamic_bg_001@2x" ofType:@"png"]]];
    // 查询工具条
    // 实例化查询条
	_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 43.5f)];
    // 键盘格式
	_searchBar.keyboardType = UIKeyboardTypeTwitter;
    // 实现委托
    _searchBar.placeholder = _L(@"holder_07");   //请输入姓名首字母
	_searchBar.delegate = (id)self;
    _searchBar.showsScopeBar = YES;
    _searchBar.keyboardType = UIKeyboardTypeASCIICapable;
    
    //去掉搜索框背景
    for (UIView *subview in _searchBar.subviews)
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [subview removeFromSuperview];
            break;
        }
    }
    
    [headerView addSubview:_searchBar];
    // 表头加入查询条
	self.tableView.tableHeaderView = headerView;
    
    //实例化搜索用的UISearchDisplayController
	__searchDisplayController = [[CustomUISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
	__searchDisplayController.searchResultsDataSource = self;
	__searchDisplayController.searchResultsDelegate = self;
    __searchDisplayController.searchBar.barStyle = nil;
    __searchDisplayController.delegate = self;
    __searchDisplayController.searchBar.backgroundColor = [UIColor clearColor];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_dismissWhenDidApprear) {
        
        [self dismissModalViewControllerAnimated:false];
    }

    if (!_isRequestedFriends) {
        
        MoonHTTPRequest* request = [[MoonHTTPRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_BABY];
        request.progressOn = true;
        request.progressTitle = _L(@"title_loading_01");
        [request onSuccess:^(id result) {

            if ([result[@"status"] intValue] == 1) {
                
                NSData* encodeDate = [[NSData alloc] initWithBase64Encoding:result[@"data"]];
                NSString* encode = [[NSString alloc] initWithData:encodeDate encoding:NSUTF8StringEncoding];

                if (encode.length > 0) {
                    
                    _friends = [NSArray arrayWithArray:[encode componentsSeparatedByString:@","]];
                    [self.tableView reloadData];
                }
                
                _isRequestedFriends = true;
            }
            else {
                
                [Helper showAlertWithTitle:result[@"message"] andMessage:nil];
            }

        } onFailure:^(NSError *error) {
            
            [Helper showAlertWithTitle:_L(@"title_networkunavailabe") andMessage:nil];
        }];
        [request asynchronous];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    
    if (self.tableView == tableView) {
        if (_dataSource.count > 0) {
            return 27;
        }
        
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (self.tableView == tableView) {
        if (_dataSource.count > 0) {
            // 根据不同的分区索引中的数组元素个数进行 return
            return [[_addressBookSections objectAtIndex:section] count];
            
        }
    }else{
        return [_filteredAddressBook count];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
        
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 13, 15, 15)];
        imageView.image = [UIImage imageNamed:@"dynamic_icon_003"];
        [cell.contentView addSubview:imageView];
        
        
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 10, 240, 20)];
        nameLabel.font = _SYS_FONT_004;
        [cell.contentView addSubview:nameLabel];
        
        
        UIImageView* checkImageView = [[UIImageView alloc] initWithFrame:CGRectMake(270, 13, 18, 18)];
        checkImageView.hidden = true;
        [cell.contentView addSubview:checkImageView];
        
        
        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(230, 13, 60, 20)];
        label.hidden = true;
        label.backgroundColor = [UIColor clearColor];
        label.font = _SYS_FONT_003;
        label.text = _L(@"title_103");
        label.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:label];
    }
    
    NSMutableDictionary* people;
    // 普通表视图
    if (self.tableView == tableView) {
        // 得到分区数组中当前分区当前行，对应的对象
        people = [[_addressBookSections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }
    // 查询表视图
    else {
        // 得到查询数组中对应当前行，对应的对象
        people = [_filteredAddressBook objectAtIndex:indexPath.row];
    }
    
    
//    NSMutableDictionary* people = [[_addressBookSections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = [people objectForKey:@"name"];
    ((UIImageView *)[cell.contentView.subviews objectAtIndex:2]).image = [[people objectForKey:@"status"] integerValue] ? [UIImage imageNamed:@"com_icon_011"] : [UIImage imageNamed:@"com_icon_010"];

    //如果用户的电话号码在_friends里面，就说明这个行是已邀请的用户，就显示label，隐藏image
    NSArray* mobiles = people[@"mobiles"];

    BOOL isInvitated = false;
    for (int i = 0; i < mobiles.count; i++)
    {
        for (int j = 0; j < _friends.count; j++)
        {
            NSString* mobile = [Helper cleanPhone:mobiles[i][@"mobile"]];
//            NSLog(@"+++ %@ : %@", mobile, _friends[j]);
            if ([mobile isEqualToString:_friends[j]]) {

                //一旦发现电话匹配，立即停止本次
                isInvitated = true;
                break;
                
            }
        }
        
        //一旦发现电话匹配，立即停止本次
        if (isInvitated) {
            break;
        }
    }

    //根据匹配结果，决定显示勾选框或提示文字
    if (isInvitated) {
        
        ((UIView *)[cell.contentView.subviews objectAtIndex:2]).hidden = true;
        ((UIView *)[cell.contentView.subviews objectAtIndex:3]).hidden = false;
    }
    else {
        ((UIView *)[cell.contentView.subviews objectAtIndex:2]).hidden = false;
        ((UIView *)[cell.contentView.subviews objectAtIndex:3]).hidden = true;
    }

    
    return cell;
}

// 分区标题头(分区栏最上面出现对应abc...)
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.tableView == tableView) {
        // 存在本地联系人数据
        if (_dataSource.count > 0) {
            // 如果当前分区对应数组中没有数据
            if ([[_addressBookSections objectAtIndex:section] count] > 0) {
                // 返回26个英文字母+1个＃号特殊字符中,指定分区索引的一个字母
                // 截取字符串解析  (26个英文字母+1个＃号特殊字符,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
                NSString *headerTitleString = [NSString stringWithFormat:@"%@", [[ALPHA substringFromIndex:section] substringToIndex:1]];
                
                return headerTitleString;
            }
        }
    }
    
    return nil;
}

// 右侧A-Z
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //正常表
    if (self.tableView == tableView) {
        // 存在本地地址薄数据
        if (_addressBookSections.count > 0) {
            NSMutableArray *indices = [NSMutableArray array];
            // 26个英文字母+1个＃号特殊字符
            for (int i = 0; i < 27; i++) {
                // 将首字母加入数组
                // 截取字符串解析  (26个英文字母中,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
                [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
            }
            return indices;
        }
    }
    
    // 查询表
	return nil;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    NSMutableDictionary* people;
    // 普通表视图
    if (self.tableView == tableView) {
        // 得到分区数组中当前分区当前行，对应的对象
        people = [[_addressBookSections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
    }
    // 查询表视图
    else {
        // 得到查询数组中对应当前行，对应的对象
        people = [_filteredAddressBook objectAtIndex:indexPath.row];
    }
    
    NSMutableArray *mobiles = [people objectForKey:@"mobiles"];
    
    //如果用户的电话号码在_friends里面，就说明这个行是已邀请的用户，就没有动作
    for (int i = 0; i < mobiles.count; i++)
    {
        for (int j = 0; j < _friends.count; j++)
        {
            NSDictionary* mobile = mobiles[i];
//            NSLog(@"....%@ %@", mobile[@"mobile"], _friends[j]);
            
            if ([mobile[@"mobile"] isEqualToString:_friends[j]]) {
//                NSLog(@"....y");
                return;
            }
//            NSLog(@"....x");
        }
    }
    
    //判断用户的电话个数，如果为1，那么就不用弹出框；否则要弹出选择框
    if (mobiles.count == 1) {
        
        //标记被选中的手机号码
        NSMutableDictionary *mobile = [mobiles objectAtIndex:0];
        
        int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
        
        [mobile setValue:(mobileStatus ? @"0" : @"1") forKey:@"status"];
        
        //标记被选中的联系人
        int status = [[people objectForKey:@"status"] integerValue];
        
        [people setValue:(status ? @"0" : @"1") forKey:@"status"];
        
        //同时更新最初数据源中对应的值
        [[_dataSource objectAtIndex:[_dataSource indexOfObject:people]] setValue:(status ? @"0" : @"1") forKey:@"status"];
        
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        ((UIImageView *)[cell.contentView.subviews objectAtIndex:2]).image = !status ? [UIImage imageNamed:@"com_icon_011"] : [UIImage imageNamed:@"com_icon_010"];
        
        //添加被标记的联系人的姓名
        if ([[people objectForKey:@"status"] integerValue]) {
            [_names addObject:[people objectForKey:@"name"]];
        }else{
            [_names removeObject:[people objectForKey:@"name"]];
        }
        
//        //用户通过searchVC中的tableview选中的话，需要reloaddata
//        if (self.tableView != tableView) {
//            [self.tableView reloadData];
//        }
        _canRefreshTableView = YES;
        
    }else if (mobiles.count > 1){
        
        //实例化一个MLTableAlert
        MLTableAlert *alert = [MLTableAlert tableAlertWithTitle:_L(@"alert_20") cancelButtonTitle:_L(@"btn_no_01") numberOfRows:^NSInteger (NSInteger section){
            
            return mobiles.count;
            
        }andCells:^UITableViewCell* (MLTableAlert *anAlert, NSIndexPath *indexPath){
            
            static NSString *CellIdentifier = @"CellIdentifier";
            UITableViewCell *cell = [anAlert.table dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if (cell == nil){
                
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            NSMutableDictionary *mobile = [mobiles objectAtIndex:indexPath.row];
            
            int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
            
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [mobile objectForKey:@"mobile"]];
            
            
            //根据mobileStatus判断电话号码是否被标记过
            if (mobileStatus == 1) {
                
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            return cell;
        }];
        
        // Setting custom alert height
        alert.height = 200;
        
        // configure actions to perform
        [alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
            
            
            
            
            //记住被点击的号码,mobile对象分为stauts和mobile两个属性，status主要用于记录此号码是否被点击过，
            NSMutableDictionary *mobile = [mobiles objectAtIndex:selectedIndex.row];
            
            int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
            
            
            if (mobileStatus == 0) {
                
                //点击某一行后，先清空上一次标记的号码，再标记当前被点击的号码行
                //遍历一次号码，将status为1的置为0。
                for (int i = 0; i < mobiles.count; i++) {
                    
                    NSMutableDictionary *mobile = [mobiles objectAtIndex:i];
                    
                    int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
                    
                    if (mobileStatus == 1) {
                        
                        [mobile setValue:@"0" forKey:@"status"];
                        
                        UITableViewCell* MLTableCell = [alert.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                        MLTableCell.accessoryType = UITableViewCellAccessoryNone;
                    }
                }
                
                [mobile setValue:@"1" forKey:@"status"];
                
                
            }
            
            //如果这次点击的号码和上次点击的号码是一样的 就要去掉标记 更新数据源
            else if (mobileStatus == 1)
            {
                [mobile setValue:@"0" forKey:@"status"];
            }
            
            
            //一个联系人中，只能有一个号码被选中
            UITableViewCell* MLTableCell = [alert.table cellForRowAtIndexPath:selectedIndex];
            
            mobileStatus = [[mobile objectForKey:@"status"] integerValue];
            
            if (mobileStatus == 1) {
                
                MLTableCell.accessoryType = UITableViewCellAccessoryCheckmark;
            }else{
                
                MLTableCell.accessoryType = UITableViewCellAccessoryNone;
            }
            
            //此用户所有电话中有一个被标记就应该标记此用户，否则不标记此联系人
            
            BOOL marked = NO;
            
            for (int i = 0; i < mobiles.count; i++) {
                
                NSMutableDictionary *mobile = [mobiles objectAtIndex:i];
                
                int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
                
                if (mobileStatus == 1) {
                    
                    marked = YES;
                    
                    
                }
            }
            
            UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            
            if (marked) {
                
                [people setValue: @"1" forKey:@"status"];
                
                //同时更新最初数据源中对应的值
                [[_dataSource objectAtIndex:[_dataSource indexOfObject:people]] setValue:@"1" forKey:@"status"];
                ((UIImageView *)[cell.contentView.subviews objectAtIndex:2]).image = [UIImage imageNamed:@"com_icon_011"];
                
                //添加被标记的联系人的姓名
                if (![_names containsObject:[people objectForKey:@"name"]]) {
                    [_names addObject:[people objectForKey:@"name"]];
                }
                
            }else{
                
                [people setValue: @"0" forKey:@"status"];
                
                //同时更新最初数据源中对应的值
                [[_dataSource objectAtIndex:[_dataSource indexOfObject:people]] setValue:@"0" forKey:@"status"];
                ((UIImageView *)[cell.contentView.subviews objectAtIndex:2]).image = [UIImage imageNamed:@"com_icon_010"];
                
                //移除被标记的联系人姓名
                [_names removeObject:[people objectForKey:@"name"]];
            }
            
            _canRefreshTableView = YES;

            
        } andCompletionBlock:^{
        
            
        }];
        
        // show the alert
        [alert show];
        
        
    }else if (mobiles == nil || mobiles.count == 0){
        
        [Helper showAlertWithTitle:@"" andMessage:_L(@"此联系人没有可用的电话号码")];
        return;
    }
    
}


#pragma mark - 返回按钮流程

/*!
 @abstract 返回按钮事件
 */
- (void) backButtonEvent
{
    if (_names.count > 0) {

        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_86") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else {
        [self.navigationController popViewControllerAnimated:true];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController popViewControllerAnimated:true];
    }
}

#pragma mark - 自定义事件
/*!
 @abstract 邀请按钮事件
 将被用户选中的联系人的电话号码组成的集合 传递给短消息发送组件
 */
- (void)inviteButtonEvent:(id)sender
{
    NSMutableArray* recipients = [[NSMutableArray alloc] init];
    for (NSDictionary* dict in _dataSource) {
        
        if ([[dict objectForKey:@"status"] integerValue]) {
        
            Contact* contact = [[Contact alloc] init];
            contact.status = false;
            contact.name = dict[@"name"];
            
            //从号码数组中选择status=1的号码和姓名
            NSMutableArray* mobiles = [dict objectForKey:@"mobiles"];
            
            for (int i = 0; i < mobiles.count; i++) {
                
                NSMutableDictionary *mobile = [mobiles objectAtIndex:i];
                
                int mobileStatus = [[mobile objectForKey:@"status"] integerValue];
                
                NSString *mobileNum = [mobile objectForKey:@"mobile"];
                
                if (mobileStatus == 1 && mobileNum != nil && mobileNum.length > 0) {
                    
                    contact.mobile = [Helper cleanPhone:mobileNum];
                }
            }
            
            [recipients addObject:contact];
        }
    }
    
    if (recipients.count == 0) {
        
        [Helper showAlertWithTitle:_L(@"alert_131") andMessage:nil];
        return;
    }

    //选中的人应该向服务器验证，那些已经是农户宝用户了
    
    //产生加密的电话号码
    NSMutableArray* mobiles = [[NSMutableArray alloc] init];
    for (Contact* contact in recipients) {
        
        [mobiles addObject:contact.mobile];
    }
    
    NSString* mobilesString = [mobiles componentsJoinedByString:@","];
    NSString* encode = [Helper encryptPhoneNumber:mobilesString];
    
    //向服务器请求
    MoonHTTPRequest* request = [[MoonHTTPRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_PHONEBOOK];
    request.progressOn = true;
    request.progressTitle = _L(@"title_loading_01");
    [request setParameter:encode forName:@"phoneBook"];
    [request onSuccess:^(id result) {

        //请求成功后，遍历要邀请的人，和返回的数据做对比，如果电话号码一样，就标志为是已注册用户
        if ([result[@"status"] intValue] == 1) {
            
            for (Contact* contact in recipients) {

                for (NSDictionary* frient in result[@"data"]) {
                    
                    if ([contact.mobile isEqualToString:[Helper decryptCiphertext:frient[@"mobile"]]]) {
                        
                        contact.status = true;
                        break;
                    }
                }
            }
            
            //然后到邀请界面
            InvitationMessageViewController* messageViewController = [[InvitationMessageViewController alloc] init];
            messageViewController.contactsToInvite = recipients;
            [self.navigationController pushViewController:messageViewController animated:true];
        }
        else {
            
            [Helper showAlertWithTitle:result[@"message"] andMessage:nil];
        }
        
    } onFailure:^(NSError *error) {
        
        [Helper showAlertWithTitle:_L(@"title_networkunavailabe") andMessage:nil];
    }];
    [request asynchronous];
}

#pragma mark - 私有方法

/*!
 @abstract 从用户的通讯录中载入联系人数据
 */
-(void)loadContacts
{
    ABAddressBookRef addressBookRef = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        //等待同意后向下执行
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_semaphore_signal(sema);
                                                 });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else
    {
        addressBookRef = ABAddressBookCreate();
    }
    
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    NSArray* systemAddressBook = CFBridgingRelease(arrayRef);

    if (systemAddressBook.count <= 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_22")];
        return;
    }
    
    for (int i = 0; i < systemAddressBook.count; i++) {
        //转换一个联系人出来
        ABRecordRef recordRef = (__bridge ABRecordRef)[systemAddressBook objectAtIndex:i];//CFBridgingRetain([systemAddressBook objectAtIndex:i]);

        // 获*取联系人记录id
        NSNumber* sysID = [NSNumber numberWithInt:(ABRecordGetRecordID(recordRef))];
        // 获取联系人记录首名并赋值
        NSString* firstName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonFirstNameProperty));
        // 获取联系人记录末名并赋值
        NSString* lastName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonLastNameProperty));
        
        NSString* fullName = [NSString stringWithFormat:@"%@ %@", (lastName ? lastName : @""), (firstName ? firstName : @"")];
        
        NSString *mobile;
        NSMutableArray *mobiles;
        ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
        if (ABMultiValueGetCount(phoneMulti) != 0) {
            
            if (mobiles == nil) {
                mobiles = [[NSMutableArray alloc] init];
            }
            
            //将电话数组置为空，进行下一次遍历
            if (mobiles.count != 0) {
                [mobiles removeAllObjects];
            }
            
            for (int k = 0; k < ABMultiValueGetCount(phoneMulti); k++) {
                
                CFStringRef numberRef = ABMultiValueCopyValueAtIndex(phoneMulti, k);
                
                mobile = CFBridgingRelease(numberRef);
                
                //获得一个联系人的所有电话
                [mobiles addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:mobile, @"mobile", @"0", @"status", nil]];
            }
        }
        
        CFRelease(phoneMulti);
        CFRelease(recordRef);
        

        [_dataSource addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:sysID, @"sysID", fullName, @"name", mobiles, @"mobiles", @"0", @"status", nil]];
        
    }
    
//    [self.tableView reloadData];
}

/*!
 @abstract 获得分区数组，即每个section下的联系人数组。
 @param localAddressBook 通讯簿中联系人集合
 @result 分区后的数组
 */
- (NSArray *)addressBookSections:(NSArray *)localAddressBook
{
    NSMutableArray* sections = [[NSMutableArray alloc] init];
    
    // 组装分区表初始默认数组
    // 循环将27个数组加入 分区数组(27个数组代表26个英文字母+1个＃号特殊字符)
    for (int i = 0; i < 27; i++) {
        [sections addObject:[NSMutableArray array]];
    }
    
    // 循环姓名数组
    for (NSMutableDictionary* person in _dataSource) {
        // 得到当前元素姓名
        NSString *contactsName = [person objectForKey:@"name"];
        
        // 1、得到姓名0索引位置的字符
        // 2、调用pinyin类实例方法pinyinFirstLetter并传入字符，判断传入的字符是汉字还是英文，如果是汉字返回汉字所属的字母，不属于汉字返回传入字符
        // 3、将拼音方法传回的字符组装成字符串
        // 4、并转换成大写格式
        NSString *sectionPinYinLetter = nil;
        NSUInteger firstLetterLocation = NSNotFound;
        //长度检查，空名字不截取
        if (contactsName != nil && contactsName.length > 0) {
            sectionPinYinLetter = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([contactsName characterAtIndex:0])] uppercaseString];
            firstLetterLocation = [ALPHA rangeOfString:[sectionPinYinLetter substringToIndex:1]].location;
        }
        
        // 1、截取sectionUgoName的第一个字符
        // 2、并判断此字符在26个英文字母+#号的位置，并赋值
        
        // 如果在26个之中的字母组成数组中有这个位置
        if (firstLetterLocation != NSNotFound) {
            // 找到ugo分区数组，在这个索引位置对应的数组，并加入同样属于索引i对应元素，及UgoContacts类的对象
            [[sections objectAtIndex:firstLetterLocation] addObject:person];
        }
        // 否则不在26个英文字母之中，用ALPHA数组最后一个特殊#号位置数组统一加入管理
        else {
            [[sections objectAtIndex:[ALPHA length] - 1] addObject:person];
        }
    }
    return sections;
}

/*!
 @abstract 初始化分区数据(组装分区数组、姓名数组、根据abc...z  26个字母对应26个分区+1个特殊分区＃号，对应字母分区放入对应姓名字母开头实体)
 */
- (void) sectionInitData
{
    // 查看通讯簿是否存在数据
    if ([_dataSource count] > 0) {
        // 清除以前分区数据
        _addressBookSections = nil;
        
        // 获取新分区数据
        _addressBookSections = [self addressBookSections:(NSArray *)_dataSource];
    }
    
}

#pragma mark - SMS Delegate

// 短信发送状态通知协议方法
//
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{    
    switch (result)
    {
        case MessageComposeResultCancelled:
            break;
        case MessageComposeResultSent: {
            //请求
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_ADD];
            NSString* mobiles = [[controller.recipients componentsJoinedByString:@","] stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSString *names = [[_names componentsJoinedByString:@"♀"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            [request setValue:names forParameter:@"names"];
            [request setValue:mobiles forParameter:@"mobiles"];
            [request setValue:[_circle objectForKey:@"id"] forParameter:@"circleId"];
            NSDictionary* dict = [request synchronous];

            JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
            if (jmf.status == JMStatusSucceed) {
                self.title = @"";
                self.navigationItem.leftBarButtonItem.enabled = false;
                self.navigationItem.rightBarButtonItem.enabled = false;
                
                self.view = [[UIView alloc] initWithFrame:self.view.frame];
                self.view.backgroundColor = [UIColor whiteColor];
                [Helper showAllTextDialog:_L(@"title_loading_07") inView:self.view];    //正在发送
                
                _dismissWhenDidApprear = true;
            }
            else {
                
                [Helper easyShowJMFStatus:jmf];
            }
        }
            
            break;
        case MessageComposeResultFailed:
            break;
        default:
            break;
    }

    //必须放在这里，要让case 1内的语句先执行，才能使viewDidAppear获取到正确的值
    [controller dismissModalViewControllerAnimated:true];
}

#pragma mark - UISearchBar delegate

-(void)searchBar:(UISearchBar *)aSearchBar textDidChange:(NSString *)searchText
{
    
    if (_filteredAddressBook != nil && _filteredAddressBook.count != 0) {
        [_filteredAddressBook removeAllObjects];
    }
    
    // 获取符合条件的数组
    _filteredAddressBook = [Helper filterAddressBook:(NSArray *)_dataSource withString:aSearchBar.text];
}

#pragma mark - UISearchDisplayDelegate delegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton=YES;

    searchBar.showsCancelButton = YES;
    
    //修改searchbar的取消按钮的title为“返回”
    for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *sbtn = (UIButton *)cc;
            [sbtn setTitle:_L(@"btn_back_01")  forState:UIControlStateNormal];    //返回
//            [sbtn addTarget:self action:@selector(refreshTableView:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    if (_canRefreshTableView) {
        [self.tableView reloadData];
    }

}


@end
